<template>
  <div class="model-form">
    <el-page-header @back="goBack" content="增加商品">
    </el-page-header>
    <div class="model-content">
      <el-form ref="ruleForm" :rules="rules" :model="form" label-width="160px">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="商品主图" prop="logo">
              <avatar v-model="form.logo"></avatar>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" name="name">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="商品状态" prop="state">
              <el-select style="width: 100%;" v-model="form.state" filterable clearable
                         placeholder="请选择">
                <el-option v-for="item in stateOptions" :key="item.id"
                           :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" name="price">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="标准售价" prop="standardPrice">
              <el-input v-model="form.standardPrice" name="standardPrice">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="批发价" prop="wholesalePrice">
              <el-input v-model="form.wholesalePrice" name="wholesalePrice">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="配送价" prop="deliveryPrice">
              <el-input v-model="form.deliveryPrice" name="deliveryPrice">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="销价1" prop="salePrice1">
              <el-input v-model="form.salePrice1" name="salePrice1">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="销价2" prop="salePrice2">
              <el-input v-model="form.salePrice2" name="salePrice2">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="销价3" prop="salePrice3">
              <el-input v-model="form.salePrice3" name="salePrice3">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="销价4" prop="salePrice4">
              <el-input v-model="form.salePrice4" name="salePrice4">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="最低售价" prop="minPrice">
              <el-input v-model="form.minPrice" name="minPrice">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="最高售价" prop="maxPrice">
              <el-input v-model="form.maxPrice" name="maxPrice">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select style="width: 100%;" v-model="form.unit" filterable clearable
                         placeholder="请选择">
                <el-option v-for="item in unitOptions" :key="item.id"
                           :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="24">
            <el-form-item label="商品简介" prop="summary">
              <el-input v-model="form.summary" name="summary" type="textarea"></el-input>
            </el-form-item>

          </el-col>
          <el-col :span="24">
            <div style="margin-left: 160px;">
              <sc-editor v-model="form.note" placeholder="请输入" style="width: 100%;" :height="400"></sc-editor>
            </div>

          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="stockNum">
              <el-input v-model="form.stockNum" name="stockNum">
              </el-input>
            </el-form-item>

          </el-col>

          <el-col :span="22">
            <el-form-item label="是否开启规格" prop="skuEnable">
              <el-switch v-model="form.skuEnable">
              </el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="22" v-if="form.skuEnable">
            <template v-for="(item, index) in form.specs" :key="item.key">
              <el-form-item size="mini" :label="'规格' + (index + 1)">
                <div style="width: 100%;">
                  <el-input v-model="item.name" style="width: 500px;" placeholder="请输入规格名称"></el-input>
                  <el-button @click.prevent="removeSpec(index)">删除</el-button>
                </div>
                <div style="margin:8px 5px">
                  <template v-for="(temp,j) in item.values" :key="j">
                    <div style="margin:6px 5px;display: inline-block;">
                      <el-input @change="updateSpecValue(index,j)" v-model="temp.name"
                                style="width: 200px;display: inline-block;" placeholder="请输入规格值">
                      </el-input>
                      <el-button @click.prevent="removeSpecValue(index,j)" type="danger"
                                 style="margin-right: 15px;">删除
                      </el-button>
                    </div>
                  </template>
                  <el-button @click.prevent="addSpecValue(index)">添加规格值</el-button>
                </div>
              </el-form-item>
            </template>

            <el-form-item label="" size="mini">
              <el-button @click.prevent="addSpec" v-if="form.specs && form.specs.length<2" type="primary">添加规格</el-button>
            </el-form-item>
          </el-col>

          <el-col :span="22" v-if="form.skuEnable">
            <el-form-item label="规格详情" size="mini">
              <el-table v-loading="loading" :data="form.skus" style="width: 100%;font-size: 12px;">
                <el-table-column label="sku名称" prop="name" width="150">
                </el-table-column>
                <el-table-column label="原价" prop="price" sortable="custom" width="200">
                  <template #default="scope">
                    <el-input v-model="scope.row.price" size="mini" name="sortNum" :min="0"
                              :max="10000">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="销售价" prop="mealFee" width="200">
                  <template #default="scope">
                    <el-input v-model="scope.row.mealFee" size="mini" name="sortNum" :min="0"
                              :max="10000">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="库存" prop="stockNum" width="200">
                  <template #default="scope">
                    <el-input-number v-model="scope.row.stock" size="mini" name="sortNum" :min="0"
                                     :max="10000">
                    </el-input-number>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>

          <el-col :span="22">
            <el-form-item>
              <el-button @click="goBack">取消</el-button>
              <el-button type="primary" @click="updateData">确定</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import nbSelect from "@/components/nbSelect.vue";
import {defineAsyncComponent, onMounted} from "vue";

const scEditor = defineAsyncComponent(() => import('@/components/scEditor/index.vue'));
import avatar from "@/components/avatar.vue";
import {ref} from "vue";
import {useData} from "@/utils/useData";
import {useCreate} from "@/uses/useCreate";
import {ElLoading, ElMessage} from 'element-plus';
import http from "@/utils/request";
import {generateSkuCombinations} from "@/utils/skuGenerator";
import {useRouter} from 'vue-router';
import {useUpdate} from "@/uses/useUpdate.js";
import {postData, postList} from "@/uses/handleData.js";

const router = useRouter();

const form = ref({
  logo: null,
  name: null,
  state: null,
  price: null,
  standardPrice: null,
  wholesalePrice: null,
  deliveryPrice: null,
  salePrice1: null,
  salePrice2: null,
  salePrice3: null,
  salePrice4: null,
  minPrice: null,
  maxPrice: null,
  unit: null,
  summary: null,
  note: null,
  stockNum: null,
  skuEnable: false,
  specs: [],
  skus: []
})

const rules = ref({
  name: [
    {required: true, message: '请输入商品名称', trigger: 'blur'}
  ],
  price: [
    {required: true, message: '请输入价格', trigger: 'blur'}
  ],
  standardPrice: [
    {required: true, message: '请输入标准售价', trigger: 'blur'}
  ],
})

const ruleForm = ref(null);
const {listData: stateOptions} = useData("/state/list")
const {listData: unitOptions} = useData("/unit/list")

const loading = ref(false)

const loadExtData = async (res) => {
  if (!res.skuEnable) {
    return
  }

  let param = {};
  param.productId = res.id;
  let skuList = await postList("product_sku_simple_list", param)
  if (skuList.code === 200) {
    form.value.skus = skuList.data;
  }

  let specsList = await postList("product_spec_simple_list", param)
  if (specsList.code === 200) {
    form.value.specs = specsList.data;
  }
}

const {updateData, goBack} = useUpdate("product", form, ruleForm, loadExtData)


// 更新SKU列表
const updateSku = () => {
  if (form.value.specs.length === 0) {
    form.value.skus = [];
    return;
  }

  // 转换规格数据格式
  const formattedSpecs = form.value.specs.map(spec => ({
    name: spec.name,
    value: spec.values.map(v => ({name: v.name}))
  }));

  // 使用skuGenerator生成SKU组合
  const skuCombinations = generateSkuCombinations(formattedSpecs);

  // 转换为表格所需的格式
  form.value.skus = skuCombinations.map(sku => ({
    name: sku.name,
    price: '',
    mealFee: '',
    stockNum: '',
    specValues: sku.specValues
  }));
}

// 添加规格
const addSpec = () => {
  form.value.specs.push({
    name: '',
    values: [],
    key: Date.now()
  });
}

// 删除规格
const removeSpec = (index) => {
  if (index > -1) {
    form.value.specs.splice(index, 1);
    updateSku();
  }
}

// 添加规格值
const addSpecValue = (item) => {
  let temp = form.value.specs[item];
  if (temp.values == undefined || temp.values == null) {
    temp.values = [];
  }
  temp.values.push({name: ""});
  updateSku();
}

// 更新规格值
const updateSpecValue = (item, select) => {
  let temp = form.value.specs[item];
  let selectTemp = form.value.specs[item].values[select];
  if (select > -1) {
    for (let index = 0; index < temp.values.length; index++) {
      var element = temp.values[index];
      if (select !== index) {
        if (element.name === selectTemp.name) {
          ElMessage.error("不能出现相同的规格值");
          selectTemp.name = "";
        }
      }
    }
  }
  updateSku();
}

// 删除规格值
const removeSpecValue = (item, index) => {
  let temp = form.value.specs[item];
  if (index > -1) {
    temp.values.splice(index, 1)
  }
  updateSku();
}

</script>

<style scoped>
</style>
